<template>
  <div class="createEasyReport">
    <div class="left">
      <el-select v-model="dataPackageCode" @change="dataPackageChangeHandler">
        <el-option
          v-for="item in jmfDataPackageOptions"
          :key="item.code"
          :value="item.code"
          :label="item.name"
        />
      </el-select>
      <el-tree
        ref="tree"
        v-loading="treeLoading"
        :indent="10"
        :data="dataSetOptions"
        :default-checked-keys="defaultCheckedKeys"
        :props="{ children: 'children', label: 'label' }"
        node-key="id"
        show-checkbox
        @check="checkHandle"
      />
    </div>
    <div class="right">
      <div class="top">
        <el-button type="primary" size="small" @click="saveOpen = true">保存</el-button>
      </div>
      <div class="content">
        <el-table v-loading="loading" :data="easyReportData.data" class="nowrapTable showOnlyLine sortTable" border>
          <el-table-column
            v-for="(parentCol) in easyReportData.column"
            :key="parentCol.prop"
            :label="parentCol.label"
            :prop="parentCol.prop"
            v-bind="parentCol"
            align="center"
          >
            <template v-if="parentCol.children && parentCol.children.length > 0">
              <el-table-column
                v-for="(childrenCol) in parentCol.children"
                :key="childrenCol.prop"
                :label="childrenCol.label"
                :prop="childrenCol.prop"
                :width="childrenCol.width"
                show-overflow-tooltip
              >
                <template slot="header">
                  <span class="fieldName">
                    <p :title="childrenCol.label">{{ childrenCol.label }}</p>
                  </span>
                  <field-query :field-val="childrenCol" :init-list="queryParams.filter" attr-name="prop" @queryData="queryData" />
                </template>
                <template slot-scope="scope">
                  <span v-if="childrenCol.type === 'JE'">{{ moneyFormat(scope.row[childrenCol.prop]) }}</span>
                  <span v-else-if="childrenCol.type === 'RQ'">{{ parseTime(scope.row[childrenCol.prop]) }}</span>
                  <template v-else-if="scope.row[parentCol['prop']+'#children'] && !scope.row[childrenCol.prop]">
                    <p v-for="(item,i) in scope.row[parentCol['prop']+'#children']" :key="i" class="row">{{ item[childrenCol.prop] ? item[childrenCol.prop] : '&nbsp;' }}</p>
                    <!-- eslint-disable -->
                    <p v-for="n in (scope.row['col'] - scope.row[parentCol['prop']+'#children'].length)" class="row">&nbsp;</p>
                  </template>
                  <span v-else>{{ scope.row[childrenCol.prop] }}</span>
                </template>
              </el-table-column>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="checkHandle"
        />
      </div>
    </div>
    <el-dialog
      :title="$t('保存报表')"
      :close-on-click-modal="false"
      :visible.sync="saveOpen"
      width="30%"
    >
      <el-form ref="form" :model="form" :rules="rules" class="dataForm">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('报表名称')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('报表名称')" show-word-limit maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="saveOpen = false">{{ $t('取 消') }}</el-button>
        <el-button size="small" type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDataSetTreeByPackageCode } from '@/api/dev/jmf/jmfDataSet'
import { listJmfDataPackage } from '@/api/dev/jmf/jmfDataPackage'
import {
  buildEasyReport,
  checkFileNameUnique,
  exportEasyReport,
  getJmfReport,
  saveJmfReport
} from '@/api/dev/jmf/jmfReport'
import FieldQuery from '@/views/system/search/fieldQuery'

export default {
  components: { FieldQuery },
  data() {
    return {
      loading: false,
      treeLoading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      form: {
        name: undefined
      },
      defaultCheckedKeys: [],
      saveOpen: false,
      rules: {
        name: { required: true, message: this.$t('必填信息'), trigger: 'blur' }
      },
      // j魔方数据包
      jmfDataPackageOptions: [],
      dataPackageCode: undefined,
      // 数据集tree
      dataSetOptions: [],
      easyReportData: {
        column: [],
        data: []
      },
      searchQueryList: [],
      // 数据包下主数据集的必选字段ID
      mainDataChooseField: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      listJmfDataPackage().then(res => {
        this.loading = true
        this.treeloading = true
        this.jmfDataPackageOptions = res.rows
        if (res.rows && res.rows.length > 0 && !this.$route.query.reportId) {
          this.dataPackageCode = res.rows[0].code
          this.dataPackageChangeHandler(this.dataPackageCode)
        }
        if (this.$route.query.reportId) {
          getJmfReport(this.$route.query.reportId).then(res => {
            if (res.code === 200) {
              this.dataPackageCode = res.data.packageCode
              this.dataPackageChangeHandler(this.dataPackageCode)
              this.form = res.data
              this.defaultCheckedKeys = JSON.parse(res.data.fieldJson)
              this.queryParams.field = JSON.parse(res.data.reportData)
              this.queryParams.packageCode = res.data.packageCode
              this.queryParams.filter = JSON.parse(res.data.filter)
              buildEasyReport(this.queryParams).then(res => {
                this.easyReportData = res.rows
                this.total = res.total
              })
            }
          })
        }
        this.loading = false
        this.treeloading = false
      })
    })
  },
  methods: {
    checkHandle() {
      this.$nextTick(() => {
        this.loading = true
        this.queryParams.field = this.build()
        this.queryParams.packageCode = this.dataPackageCode
        buildEasyReport(this.queryParams).then(res => {
          this.easyReportData = res.rows
          this.total = res.total
          this.loading = false
        })
      })
    },
    // 数据包change事件
    dataPackageChangeHandler(val) {
      getDataSetTreeByPackageCode(val).then(res => {
        this.dataSetOptions = res.data
      })
    },
    exportEasyReportHandle() {
      this.queryParams.field = this.build()
      this.queryParams.packageCode = this.dataPackageCode
      exportEasyReport(this.queryParams).then(res => {
        console.log(res)
      })
    },
    // 解析选择的字段信息
    build() {
      const filedNodes = this.$refs.tree.getCheckedNodes(true, false)
      const field = {}
      filedNodes.forEach((item) => {
        let dataSet = []
        if (field[item.dataSetCode]) {
          dataSet = field[item.dataSetCode]
        }
        dataSet.push(item)
        field[item.dataSetCode] = dataSet
      })
      return field
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          this.form.reportData = JSON.stringify(this.build())
          this.form.fieldJson = JSON.stringify(this.$refs.tree.getCheckedKeys())
          this.form.packageCode = this.dataPackageCode
          this.form.filter = JSON.stringify(this.queryParams.filter)
          if (!this.$route.query.reportId) {
            this.form.userId = this.$store.state.user.userId
            this.form.dirId = this.$route.query.dirId
          }
          this.form.type = 'easy'
          if (this.form.id) {
            saveJmfReport(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.saveOpen = false
              } else {
                this.msgError(response.msg)
              }
              this.loading = false
            })
          } else {
            // 校验是否重名
            checkFileNameUnique(this.form.name, this.form.dirId).then(res => {
              if (res.data) {
                saveJmfReport(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess(this.$t('保存成功'))
                    this.saveOpen = false
                  } else {
                    this.msgError(response.msg)
                  }
                  this.loading = false
                })
              } else {
                this.msgError(this.$t('当前文件夹下,已有同名文件'))
                this.loading = false
              }
            })
          }
        }
      })
    },
    /**
     * 查询条件查询
     * @param data 查询条件
     * @param trigger 是否触发查询列表
     */
    queryData(data, trigger) {
      this.loading = true
      this.$nextTick(() => {
        var searchQueryTempList = []
        this.searchQueryList.forEach(item => {
          if (item.fieldName !== data.fieldName && item.value && item.value !== '') {
            searchQueryTempList.push(item)
          }
        })
        debugger
        this.searchQueryList = searchQueryTempList
        if (data && data.value && (data.value !== '' || data.conditions !== '')) {
          this.searchQueryList.push(data)
        }
        this.queryParams.filter = this.searchQueryList
        if (!trigger) {
          this.checkHandle()
        } else {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.row{
  border-bottom: 1px solid #dfe6ec;
  padding: 7px 0;
  margin: 0;
}
.row:first-child{
  padding-top: 0;
}
.row:last-child{
  border-bottom: none;
  padding-bottom: 0;
}
/deep/ .el-table .cell{
  padding-left: 0;
  padding-right: 0;
  span{
    //display: inline-block;
    //width: 100%;
    padding: 0 10px;
  }
  .row{
    padding-left: 10px;
    padding-right: 10px;
  }
}
</style>
